package org.ithasu.tools.net.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.ithasu.tools.Console;
import org.ithasu.tools.IOTools;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class ResourceHandler implements HttpHandler {

	private final static String notFound = "<html><h1>Not found</h1>Resource '%s' was not found";

	private final Class<?> baseClass;
	private final String defaultFile;

	public ResourceHandler(Class<?> baseClass, String defaultFile) {
		this.baseClass = baseClass;
		this.defaultFile = defaultFile;
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String filename = exchange.getRequestURI().toString();
		Console.message(filename);
		Console.message("---");
		for (Map.Entry<String, List<String>> e : exchange.getRequestHeaders().entrySet()) {
			Console.message(e.getKey() + ": " + e.getValue());
		}
		Console.message("---");

		// Redirect
		if (filename == null || "/".equals(filename) || filename.equals(exchange.getHttpContext().getPath())) {
			HTTPTools.writeResponse_redirect(exchange, defaultFile);
			return;
		}
		// Response
		int responseCode = 404;
		String type = "text/plain";
		byte[] data = null;
		try {
			if (filename.endsWith(".html")) {
				type = "text/html";
			} else if (filename.endsWith(".css")) {
				type = "text/css";
			} else if (filename.endsWith(".js")) {
				type = "application/javascript";
			} else if (filename.endsWith(".png")) {
				type = "image/png";
			}
			InputStream stream = baseClass.getResourceAsStream(filename);
			if (stream == null) {
				responseCode = 404;
				type = "text/html";
				data = String.format(notFound, filename).getBytes();
			} else {
				data = IOTools.read(stream);
				if (data == null) {
					responseCode = 404;
					type = "text/html";
					data = String.format(notFound, filename).getBytes();
				} else {
					responseCode = 200;
				}
			}
		} catch (Exception e) {
			Console.error("Not found : " + filename);
			Console.error(e);
			// Not found
			responseCode = 404;
			type = "text/html";
			data = String.format(notFound, filename).getBytes();
		}
		HTTPTools.writeResponse(exchange, responseCode, type, data);
	}
}
